package com.hyc.DataStructure.sort;

import java.util.Arrays;

/**
 * @projectName: DataStructure
 * @package: com.hyc.DataStructure.sort
 * @className: bubblesort
 * @author: 冷环渊 doomwatcher
 * @description: TODO
 * @date: 2022/1/4 14:21
 * @version: 1.0
 */
public class bubblesort {

    /* 冒泡排序
     * 每一次都会用一个数去对比之后的数字，一次对比一直到排序完毕
     * */
    public static void main(String[] args) {
        int arr[] = {3, 2, -1, -2, 10, 20};
        int[] test = new int[80000];
        //测试数据
        for (int i = 0; i < 80000; i++) {
            test[i] = (int) (Math.random() * 80000);
        }
        long time = System.currentTimeMillis();
        bubblesortpro(test);
        long end = System.currentTimeMillis();
        long t = ((end - time) / 1000);
        System.out.println("一共用时 " + t + "秒");
    }

    //没有优化过的冒泡排序
    public static void bubblesort(int[] arr) {
        int temp = 0;
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
            System.out.println("第" + (i + 1) + "次比较: " + Arrays.toString(arr));
        }
    }

    //  我们用boolean变量来遍历判断避免没有必要的比较
    public static void bubblesortpro(int[] arr) {
        int temp = 0;
        //用来结束标识
        boolean flag = false;
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    flag = true;
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
            if (!flag) {
                break;

            } else {
                flag = false;
            }
            //System.out.println("第" + (i + 1) + "次比较: " + Arrays.toString(arr));
        }
    }
}
